package geektime.spring.springbucks.service;

import geektime.spring.springbucks.mapper.CoffeeOrderMapper;
import geektime.spring.springbucks.model.Coffee;
import geektime.spring.springbucks.model.CoffeeOrder;
import geektime.spring.springbucks.model.OrderState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.*;

@Slf4j
@Transactional
@Service
public class CoffeeOrderService {
    @Autowired
    private CoffeeOrderMapper orderRepository;
    @Transactional
    public Long createOrder(String customer, Coffee coffee) {
        CoffeeOrder order = CoffeeOrder.builder()
                .customer(customer)
                .items(new ArrayList<>(Arrays.asList(coffee)))
                .state(OrderState.INIT)
                .build();
        Map m1=new HashMap();
        m1.put("customer",customer);
        m1.put("state",OrderState.INIT.ordinal());
        Long saved = orderRepository.createOrder(m1);
        Map m=new HashMap();
        m.put("coffee_order_id",saved);
        m.put("items_id",order.getItems().get(0).getId());
        log.info("insert t_oder_coffee", orderRepository.createOrderCoff(m));
        log.info("New Order: {}", saved);

        return saved;
    }

    public List<Map> selectorder(Long id) {

        return orderRepository.selectorder(id);
    }
    public int selectordercount(Long id) {

        return orderRepository.selectordercount(id);
    }

    public boolean updateState( OrderState state,Long id) {
        List<Map> order =orderRepository.selectorder(id);
        Map m=new HashMap();
        for(int i=0;i<order.size();i++){
           int s=(int)order.get(i).get("STATE");

           int  yy=state.ordinal();
            boolean a=  s >  state.ordinal();
          if (a){
              log.warn("Wrong State order: {}, {}", state);
              continue;
          }
            orderRepository.updateState( state.ordinal() ,id);
        }

        log.info("Updated Order: {}", orderRepository.selectorder(id));
        return true;
    }


    public void deleteorder(Long id){
        int i=orderRepository.deleteorder(id);
        if(i>0) {
            orderRepository.deleteordercoffe(id);
        }
    }
    @Transactional
    public void deleteorderbak(Long id) throws Exception {
        int i=orderRepository.deleteorder(id);
        if(i==1) {
             throw new RuntimeException();
        }

    }

}
